﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using Auth.Application;
using Auth.SqlSugar.IocManager;
using Auth.Web.Filter;
using Autofac.Extensions.DependencyInjection;
using Auth.SqlSugar;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace Auth.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                 .SetBasePath(env.ContentRootPath)
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
            //初始化映射关系
            AuthMapper.Initialize();
        }

        public IConfiguration Configuration { get; }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            DbInstance.DB_ConnectionString = Configuration.GetConnectionString("MysqlConnection");
            DbInstance.Redis_ConnectionString = Configuration.GetConnectionString("RedisConnection");
            //注册全局 异常类
            services.AddMvcCore(item =>
            {
                item.Filters.Add<CustomerExceptionFilterAttribute>();
            });
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            //session 注册
            services.AddSession(item =>
            {
                item.IdleTimeout = TimeSpan.FromDays(7);
            });
            return new AutofacServiceProvider(IocManager.InitAutofac(services));//第三方IOC接管 core内置DI容器
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory factory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Shared/Error");
            }
            factory.AddConsole(Configuration.GetSection("Logging"))
                   .AddNLog()
                   .AddDebug();
            var nlogFile = System.IO.Path.Combine(env.ContentRootPath, "nlog.config");
            env.ConfigureNLog(nlogFile);
            //使用静态文件
            app.UseStaticFiles();

            app.UseCookiePolicy();
            //Session
            app.UseSession();
            //使用Mvc，设置默认路由为系统登录
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Login}/{action=Index}/{id?}");
            });
        }
    }
}